import os
import jinja2
import webapp2

from webapp2_extras import sessions
from google.appengine.api import users

from model import UserInfo

jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
jinja_environment.filters['cents'] = lambda value: '%.2f'%value if value else '-'
jinja_environment.filters['integer'] = lambda value: int(value) if value else '-'
jinja_environment.filters['if'] = lambda value,cond,velse: value if cond else velse

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.user_info = self.get_user_info(user)

        try:
            # Dispatch the request.
            result = webapp2.RequestHandler.dispatch(self)
            if result:
                (template_name, template_values) = result
                # Set some standard template values
                template_values['user_info'] = self.user_info
                template_values['logout_url'] = users.create_logout_url('/')
                # Process and write the template
                template = jinja_environment.get_template(template_name)
                self.response.out.write(template.render(template_values))
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    def get_user_info(self, user):
        result = UserInfo.all().filter('user = ', user).fetch(1)
        if len(result) == 0:
            user_info = UserInfo(user=user)
            user_info.put()
            return user_info
        else:
            return result[0]

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session(backend='memcache')